<?php

namespace App\Observers;

use App\Models\UserLog;
use App\Models\User;

class UserLogObserver
{
    public function creating(UserLog $UserLog)
    {
        $UserLogEnd = UserLog::where(['user_id'=>$UserLog->user_id,'currency_type'=>$UserLog->currency_type])->orderBy('id','desc')->first();
        if($UserLog->currency_type == 'balance') {
            $balance = User::where('id', $UserLog->user_id)->select('balance')->first()->toArray();
            $UserLogEnd = isset($UserLogEnd) ? $UserLogEnd->end : $balance['balance'];
        }elseif($UserLog->currency_type == 'btc'){
            $balance = User::where('id', $UserLog->user_id)->select('btc')->first()->toArray();
            $UserLogEnd = isset($UserLogEnd) ? $UserLogEnd->end : $balance['btc'];
        }elseif($UserLog->currency_type == 'electricity_fee'){
        	$balance = User::where('id', $UserLog->user_id)->select('electricity_fee')->first()->toArray();
        	$userLog = UserLog::where(['user_id'=>$UserLog->user_id,'currency_type'=>$UserLog->currency_type,'status'=>0])->orderBy('id','desc')->first();
        	$UserLogEnd = isset($userLog) ? $UserLogEnd->end : $balance['electricity_fee'];
        }else{
            $UserLogEnd = isset($UserLogEnd)?$UserLogEnd->end:0;
        }

        if($UserLog->in > 0){
            $UserLog->end = $UserLogEnd+$UserLog->in;
        }elseif($UserLog->out >0){
            $UserLog->end = $UserLogEnd-$UserLog->out;
        }
        
        if($UserLog->type == 20 && $UserLog->in > 0){
        	$UserLog->end = $UserLog->in;
        }elseif($UserLog->type == 20 && $UserLog->out >0){
            $UserLog->end = -$UserLog->out;
        }
    }

    /**
     * Handle the = user log "created" event.
     *
     * @param  \App\UserLog  $UserLog
     * @return void
     */
    public function created(UserLog $UserLog)
    {
        $currency_type = $UserLog->currency_type;
        if($currency_type == 'electricity_fee' && $UserLog->type == 32){
        	$UserLog->user->$currency_type = $UserLog->end;
        }
        $UserLog->user->$currency_type = $UserLog->end;
        $UserLog->user->save();
    }
}
